package com.ajiao3.preparedstatement.crud;

import com.bean.Customer;
import com.bean.Order;
import com.util.JDBCUtil;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用PreparedStatemen实现针对于不同表的通用的查询操作
 *
 */
public class PreparedStatementQueryTest {

    @Test
    public  void testGetForList(){
        CustomerForQuery customerForQuery = new CustomerForQuery();
//      String sql = "select id,name,email,birth from customers where id = ?";

//      Customer customer = customerForQuery.queryForCustomers(sql,13);

        String sql1 = "select id,name,email from customers where id <= ?";
        List<Customer> list = getForList(Customer.class, sql1, 5);
        list.forEach(System.out::println);
    }

    public <T> List<T> getForList(Class<T> clazz ,String sql, Object... args){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtil.getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            //执行
            rs = ps.executeQuery();

            //获取结果集的元数据
            ResultSetMetaData rsmd = rs.getMetaData();

            //获取列数
            int columnCount = rsmd.getColumnCount();
            //创建一个对象
            ArrayList<T> list = new ArrayList<>();
            while (rs.next()) {
                //创建一个对象
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取每个列的值:通过结果集ResultSet
                    Object value = rs.getObject(i + 1);

                    //通过元数据ResultSetMetaData
                    //只能获取列的列名getColumnName
                    //获取列的别名getColumnLabel,如果sql没有设置别名，默认的拿到列名
//                    String columnName = rsmd.getColumnName();
                    String countLabel = rsmd.getColumnLabel(i + 1);

                    //给cust对象指定的columnName属性，赋值为value，通过反射
                    //通过反射去找Customer类中对应columnName列名的属性，然后给他复制columnvalue
                    Field field = clazz.getDeclaredField(countLabel);
                    field.setAccessible(true);
                    field.set(t, value);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.CloseResource(conn, ps, rs);
        }
        return null;
    }



    @Test
    public void testGetInstance(){
//        String sql ="SELECT order_id orderId,order_name orderName,order_date orderDate FROM `order` WHERE order_id=?";
//        Order order = GetInstance(Order.class,sql, 2);
//        System.out.println(order);

        String sql1 ="SELECT id,name,email,birth FROM Customers WHERE id=?";
        Customer customer = GetInstance(Customer.class,sql1, 18);
        System.out.println(customer);
    }


    /**
     * 针对于表的字段名与类的属性名不相同的情况
     * 类的属性名于表的字段名不一时，sql得是用别名来与类的属性名一致
     * @param sql
     * @param args
     * @return
     */
    public <T> T  GetInstance(Class<T> clazz ,String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtil.getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            //执行
            rs = ps.executeQuery();

            //获取结果集的元数据
            ResultSetMetaData rsmd = rs.getMetaData();

            //获取列数
            int columnCount = rsmd.getColumnCount();

            if (rs.next()) {

                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取每个列的值:通过结果集ResultSet
                    Object value = rs.getObject(i + 1);

                    //通过元数据ResultSetMetaData
                    //只能获取列的列名getColumnName
                    //获取列的别名getColumnLabel,如果sql没有设置别名，默认的拿到列名
//                    String columnName = rsmd.getColumnName();
                    String countLabel = rsmd.getColumnLabel(i + 1);

                    //给cust对象指定的columnName属性，赋值为value，通过反射
                    //通过反射去找Customer类中对应columnName列名的属性，然后给他复制columnvalue
                    Field field = clazz.getDeclaredField(countLabel);
                    field.setAccessible(true);
                    field.set(t, value);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.CloseResource(conn, ps, rs);
        }
        return null;
    }

}
